<script setup lang="ts">
  import { ref, computed, watch, onBeforeMount } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import TableLayout from '@/layout/table-layout.vue';
  import { usePageTable } from '@/hooks/arco/usePageTable';
  import { useSkeleton } from '@/hooks/arco/useSkeleton';
  import { useModalHandler } from '@/hooks/arco/useModalHandler';
  import * as Lodash from 'lodash';
  import {
    queryStaffInfo,
    queryStaffExecuteLogs,
    queryStaffCertificates,
    resetStaffPassword,
    unBindStaffPhone,
    enableStaff,
    disableStaff,
    genSmsCode,
  } from '@/api/structure-management/employee';
  import { queryStaffRoles } from '@/api/permission';
  import {
    getGenderName,
    getDepartment,
    getPosition,
  } from '@/views/lhj-v1/util';
  import EditModal from './edit.vue';
  import FuncPermission from './permission.vue';

  const emits = defineEmits(['update']);
  const props = defineProps({
    staffId: {
      type: String,
      default: '',
    },
  });

  const baseNameMap = {
    accountId: { key: 'staffId', label: '账号ID' },
    account: { key: 'staffAccount', label: '账号' },
    accountStatus: { key: 'status', label: '状态' },
    accountPhone: { key: 'phoneNo', label: '关联电话' },
    accountPermFunc: { key: 'permFunc', label: '功能权限' },
    accountPermData: { key: 'permData', label: '数据权限' },
    workId: { key: 'id', label: '序号' },
    workDate: { key: 'workDate', label: '工作日期' },
    workContent: { key: 'workTitle', label: '工作内容' },
    customName: { key: 'elderName', label: '客户姓名' },
    itemQuals: { key: 'certificateResIds'},
    btnAction: { label: '操作' },
  };

  const dataPage = ref({
    total: 0,
    page: 1,
    pageSize: 10,
  });

  const baseInfoKeyMap: any = {
    staffId: '员工ID',
    staffName: '员工姓名',
    genderName: '员工性别',
    birthday: '出生日期',
    phoneNo: '联系电话',
    idCardNo: '身份证号',
    jobStatusTitle: '就职状态',
    department: '所属部门',
    position: '所在岗位',
  };
  const tabActiveKey = ref('base-info');
  const staffId = ref(props.staffId);
  const currentItem = ref<any>();
  const itemFuncPermissions = ref<any[]>([]);
  // const itemDataPermissions = ref<any[]>([]);
  // 基本信息
  const baseInfoComputed = computed(() => {
    const outputs: any[] = [];
    Lodash.keys(baseInfoKeyMap).forEach((key) => {
      let value = currentItem.value?.[key];
      switch (key) {
        case 'genderName': {
          value = getGenderName(currentItem.value?.gender);
          break;
        }
        case 'department': {
          value = getDepartment(currentItem.value?.departments);
          break;
        }
        case 'position': {
          value = getPosition(currentItem.value?.positions);
          break;
        }
        default: {
          break;
        }
      }
      if (!value) {
        value = '—';
      }
      outputs.push({
        key,
        value,
        label: baseInfoKeyMap[key],
      });
    });
    return outputs;
  });
  const itemFuncPermissionsComputed = computed(() => {
    const names: string[] = [];
    itemFuncPermissions.value.forEach((item) => {
      names.push(item.name);
    });
    return names.join('；');
  });
  
  // 资质证书
  const qualifications = ref({
    key: '',
    label: '资质信息',
    imgs: [] as any[],
  });

  const getStaffCertificates = () => {
    queryStaffCertificates(staffId.value)
      .then((res) => {
        qualifications.value.imgs = res;
        // editHandler.value.props.data[baseNameMap.itemQuals.key] = res;
      })
      .catch((error) => {});
  };
  
  const itemData = useSkeleton<any, any[]>({
    apiFun: queryStaffInfo,
    initQueryParams: [staffId.value],
    onSuccess(data) {
      if (data) {
        currentItem.value = data;
        getStaffCertificates();
        // console.log('currentItem:', currentItem.value);
      }
    },
  });

  const editHandler = ref({
    props: {
      data: {} as any,
      visible: false,
      title: '编辑员工',
      type: 'edit' as any,
    },
    onSave: () => {
      itemData.execute(staffId.value);
      emits('update');
    },
  });

  const getStaffPermissions = () => {
    queryStaffRoles(staffId.value)
      .then((res) => {
        itemFuncPermissions.value = res;
      })
      .catch((err) => {});
  };

  const accountComputed = computed(() => {
    const outputs: any = {};
    Lodash.keys(currentItem.value).forEach((key) => {
      let value = currentItem.value?.[key];
      switch (key) {
        case baseNameMap.accountStatus.key: {
          value = value === 1 ? '正常' : '禁用';
          break;
        }
        default: {
          break;
        }
      }
      if (!value) {
        value = '—';
      }
      outputs[key] = value;
    });
    return outputs;
  });

  // 查询表格列配置
  const tableColumns = [
    {
      title: baseNameMap.workId.label,
      dataIndex: baseNameMap.workId.key,
      // minWidth: 140,
    },
    {
      title: baseNameMap.workDate.label,
      dataIndex: baseNameMap.workDate.key,
      // minWidth: 300,
    },
    {
      title: baseNameMap.customName.label,
      dataIndex: baseNameMap.customName.key,
      // minWidth: 200,
    },
    {
      title: baseNameMap.workContent.label,
      dataIndex: baseNameMap.workContent.key,
      // minWidth: 300,
    },
    // {
    //   title: baseNameMap.btnAction.label,
    //   align: 'center' as const,
    //   dataIndex: 'action',
    //   slotName: 'action',
    //   fixed: 'right',
    //   width: 100,
    // },
  ];
  const workRecordTable = usePageTable({
    create: false,
    resetBtn: false,
    searchForm: {
      state: {
        [baseNameMap.workDate.key]: '',
        [baseNameMap.workContent.key]: '',
        [baseNameMap.customName.key]: '',
      },
    },
    table: {
      rowKey: baseNameMap.workId.key,
      fakePage: true,
      apiFun: (query) => {
        return new Promise((resolve) => {
          const params = {
            ...dataPage.value,
            workDate: query[baseNameMap.workDate.key],
            workTitle: query[baseNameMap.workContent.key],
            elderName: query[baseNameMap.customName.key],
          };
          queryStaffExecuteLogs(params).then((res) => {
            dataPage.value.total = res.total;
            resolve(res.list);
          });
        });
      },
      onSuccess(data) {
        // dataDepartments.value = getDepartmentList(data);
      },
      columns: tableColumns,
    },
  });

  const handleTabChange = (key: string) => {
    tabActiveKey.value = key;
    if (key === 'account-info') {
      getStaffPermissions();
    }
  };

  const permissionHandler = useModalHandler({
    onSuccess() {
      getStaffPermissions();
    },
  });

  // 删除员工
  const handleDelete = () => {
    //
  };

  // 重置员工密码
  const handleResetStaffPassword = () => {
    resetStaffPassword(staffId.value)
      .then((res) => {
        Message.success(res);
      })
      .catch((err) => {});
  };

  const phoneModalHandler = ref({
    visible: false,
    state: {
      phone: '',
      code: '',
    },
    handleShow: (phone: string) => {
      phoneModalHandler.value.state.phone = phone;
      phoneModalHandler.value.visible = true;
    },
    handleOk: () => {
      const data = phoneModalHandler.value.state;
      if (!data.code) {
        Message.warning('请输入验证码');
        return;
        // return;
      }
      unBindStaffPhone(staffId.value, data.code)
        .then((res) => {
          itemData.execute(staffId.value);
          Message.success(res);
          phoneModalHandler.value.visible = false;
          itemData.execute(staffId.value);
        })
        .catch((err) => {});
    },
    handleCancel: () => {
      phoneModalHandler.value.visible = false;
    },
  });

  const codeHandler = ref({
    text: '获取验证码',
    time: 59,
    disabled: false,
    timer: -1 as any,
    begin: () => {
      if (codeHandler.value.disabled) {
        return;
      }
      codeHandler.value.disabled = true;
      genSmsCode(phoneModalHandler.value.state.phone)
        .then((res) => {
          Message.success('验证码已发送');
          codeHandler.value.timer = setInterval(() => {
            if (codeHandler.value.time <= 1) {
              clearInterval(codeHandler.value.time);
              codeHandler.value.text = '获取验证码';
              codeHandler.value.time = 59;
              codeHandler.value.disabled = false;
              return;
            }
            codeHandler.value.time -= 1;
            codeHandler.value.text = `已发送(${codeHandler.value.time}s)`;
          }, 1000);
        })
        .catch((err) => {
          codeHandler.value.disabled = false;
        })
        .finally(() => {});
    },
  });

  //
  const handleEnableStaff = (status: boolean) => {
    let apiFunc = enableStaff;
    if (!status) {
      apiFunc = disableStaff;
    }
    apiFunc(staffId.value)
      .then((res) => {
        Message.success(res);
        itemData.execute(staffId.value);
      })
      .catch((err) => {});
  };

  watch(
    () => props.staffId,
    (newVal) => {
      if (newVal) {
        staffId.value = newVal;
      }
    },
    { immediate: true }
  );
  watch(
    () => currentItem.value,
    (newVal) => {
      if (newVal) {
        editHandler.value.props.data = newVal;
      }
    },
    { deep: true }
  );

  watch(()=>qualifications.value.imgs, (newVal)=>{
    editHandler.value.props.data[baseNameMap.itemQuals.key] = newVal;
  });
</script>

<template>
  <div class="m-employee-info flex-col">
    <div class="me-info-body">
      <skeleton-view v-bind="itemData.bindProps">
        <a-tabs default-active-key="base-info" @change="handleTabChange">
          <a-tab-pane key="base-info" title="基本信息">
            <ul class="me-info-body-items">
              <li
                v-for="(item, index) of baseInfoComputed"
                :key="'info-' + index"
              >
                <span class="label">{{ item.label }}</span>
                <span class="value">{{ item.value }}</span>
              </li>
              <li>
                <span class="label">{{ qualifications.label }}</span>
                <!-- <span class="value">—</span> -->
                <a-space>
                  <a-image width="100" height="100" :src="item.resourceUrl" v-for="(item, index) of qualifications.imgs" :key="'eii-' + index + item.id"/>
                </a-space>
              </li>
            </ul>
          </a-tab-pane>
          <a-tab-pane key="account-info" title="账号信息">
            <ul class="me-info-body-items">
              <li>
                <span class="label">{{ baseNameMap.accountId.label }}</span>
                <span class="value">{{
                  accountComputed[baseNameMap.accountId.key]
                }}</span>
              </li>
              <li>
                <span class="label">{{ baseNameMap.account.label }}</span>
                <span class="value">{{
                  accountComputed[baseNameMap.account.key]
                }}</span>
              </li>
              <li>
                <span class="label">{{ baseNameMap.accountStatus.label }}</span>
                <span class="value">{{
                  accountComputed[baseNameMap.accountStatus.key]
                }}</span>
                <span v-if="currentItem[baseNameMap.accountStatus.key] === 1">
                  <a-popconfirm
                    type="warning"
                    content="是否禁用员工账号？"
                    @ok="handleEnableStaff(false)"
                  >
                    <span class="action">禁用</span>
                  </a-popconfirm>
                </span>
                <span v-else>
                  <a-popconfirm
                    type="warning"
                    content="是否启用员工账号？"
                    @ok="handleEnableStaff(true)"
                  >
                    <span class="action">启用</span>
                  </a-popconfirm>
                </span>
              </li>
              <li>
                <span class="label">密码</span>
                <span class="value">******</span>
                <a-popconfirm type="warning" @ok="handleResetStaffPassword">
                  <template #content>
                    <div>
                      <div>是否确定重置为初始密码？</div>
                      <div>初始密码为：123456</div>
                    </div>
                  </template>
                  <span class="action">重置</span>
                </a-popconfirm>
              </li>
              <li>
                <span class="label">{{ baseNameMap.accountPhone.label }}</span>
                <span class="value">{{
                  accountComputed[baseNameMap.accountPhone.key]
                }}</span>
                <!-- <span v-if="accountComputed[baseNameMap.accountPhone.key]">
                  <a-popconfirm type="warning" @ok="handleUnBindStaffPhone" content="是否解绑关联电话？">
                    <span class="action">解绑</span>
                  </a-popconfirm>
                </span> -->
                <span
                  v-if="accountComputed[baseNameMap.accountPhone.key]"
                  class="action"
                  @click="
                    phoneModalHandler.handleShow(
                      accountComputed[baseNameMap.accountPhone.key]
                    )
                  "
                  >解绑</span
                >
                <span v-else class="action">绑定电话</span>
              </li>
              <li>
                <span class="label">{{
                  baseNameMap.accountPermFunc.label
                }}</span>
                <span v-if="itemFuncPermissions.length > 0" class="value">{{
                  itemFuncPermissionsComputed
                }}</span>
                <span
                  class="action"
                  @click="
                    permissionHandler.showModal({
                      staffId: staffId,
                      roles: itemFuncPermissions,
                    })
                  "
                >
                  {{ itemFuncPermissions.length > 0 ? '修改' : '设置权限' }}
                </span>
              </li>
              <!-- <li>
                <span class="label">{{ baseNameMap.accountPermData.label }}</span>
                <span class="value" v-if="itemDataPermissions.length > 0">X</span>
                <span class="action" v-if="itemDataPermissions.length > 0">修改</span>
                <span class="action" v-else>设置权限</span>
              </li> -->
            </ul>
          </a-tab-pane>
          <a-tab-pane key="work-record" title="工作记录">
            <TableLayout v-bind="workRecordTable.bindProps">
              <template #searchForm="{ state }">
                <!-- 工作日期 -->
                <a-form-item
                  :field="baseNameMap.workDate.key"
                  :label="baseNameMap.workDate.label"
                >
                  <a-date-picker
                    v-model="state[baseNameMap.workDate.key]"
                    style="width: 100%"
                    :placeholder="'请选择' + baseNameMap.workDate.label"
                  />
                </a-form-item>
                <!-- 工作内容 -->
                <a-form-item
                  :field="baseNameMap.workContent.key"
                  :label="baseNameMap.workContent.label"
                >
                  <a-input
                    v-model="state[baseNameMap.workContent.key]"
                    :placeholder="'请输入' + baseNameMap.workContent.label"
                    allow-clear
                  />
                </a-form-item>
                <!-- 客户姓名 -->
                <a-form-item
                  :field="baseNameMap.customName.key"
                  :label="baseNameMap.customName.label"
                >
                  <a-input
                    v-model="state[baseNameMap.customName.key]"
                    :placeholder="'请输入' + baseNameMap.customName.label"
                    allow-clear
                  />
                </a-form-item>
              </template>
              <!-- <template #action="{ record }">
                <a-space>
                  <a-button size="small" type="text" @click="handleLook(record)">{{ baseNameMap.btnLook.label }}</a-button>
                </a-space>
              </template> -->
            </TableLayout>
          </a-tab-pane>
        </a-tabs>
      </skeleton-view>

      <!-- 解绑手机弹窗 -->
      <a-modal
        v-model:visible="phoneModalHandler.visible"
        top="20%"
        :align-center="false"
        width="400px"
        unmount-on-close
      >
        <template #title>
          <span>解绑关联电话</span>
        </template>
        <div>
          <a-input v-model="phoneModalHandler.state.phone" readonly>
            <template #suffix>
              <span
                class="m-employee-code"
                :class="{ disable: codeHandler.disabled }"
                @click="codeHandler.begin"
                >{{ codeHandler.text }}</span
              >
            </template>
          </a-input>
          <a-input
            v-model="phoneModalHandler.state.code"
            style="margin-top: 15px"
            placeholder="请输入验证码"
          />
        </div>
        <template #footer>
          <a-button @click="phoneModalHandler.handleCancel">取消</a-button>
          <a-button type="primary" @click="phoneModalHandler.handleOk"
            >确定</a-button
          >
        </template>
      </a-modal>

      <!-- 编辑弹窗 -->
      <EditModal
        v-bind="editHandler.props"
        @cancel="editHandler.props.visible = false"
        @save="editHandler.onSave"
      />

      <!-- 功能权限编辑框 -->
      <FuncPermission v-bind="permissionHandler.bindProps" />

      <a-space
        v-show="tabActiveKey === 'base-info'"
        v-if="currentItem"
        class="me-info-body-base-btns"
      >
        <ae-button purpose="delete" disabled @click="handleDelete"
          >取消</ae-button
        >
        <ae-button purpose="edit" @click="editHandler.props.visible = true"
          >编辑</ae-button
        >
      </a-space>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .m-employee-info {
    height: 100%;
  }
  .me-info-body {
    padding: 10px;
    flex: 1;
    position: relative;

    .me-info-body-items {
      & > li {
        margin-top: 16px;
        display: flex;
      }

      .label {
        display: inline-block;
        width: 90px;
        text-align: right;
        color: var(--color-text-1);
        margin-right: 20px;
      }

      .value {
        display: inline-block;
        color: var(--color-text-2);
        min-width: 60px;
        margin-right: 20px;
      }
      .action {
        color: rgb(var(--primary-6));
        cursor: pointer;
        text-decoration: underline;
        user-select: none;
      }
    }

    .me-info-body-base-btns {
      padding-bottom: 30px;
      padding-right: 30px;
      position: absolute;
      bottom: 0;
      right: 0;
    }
  }
  .m-employee-code {
    cursor: pointer;
    color: rgb(var(--primary-6));

    &.disable {
      color: var(--color-neutral-5);
    }
  }
</style>
